/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.tnmk.worktime.service.dao;

import org.tnmk.worktime.service.dao.entry.SessionEntry;
import org.tnmk.worktime.service.dao.entry.SpendEntry;

/**
 * Handle insert/update/delete/select WorkSession from storage
 *
 * @author tnmkhoi
 */
public class SpendDao extends BaseDao<SpendEntry> {

  private static final SpendDao instance = new SpendDao();

  public static SpendDao getInstance() {
    return instance;
  }
  private SessionDao sessionDao = SessionDao.getInstance();

  private SpendDao() {
    super(SpendEntry.class);

  }

  public SpendEntry addSpend(SessionEntry session, Long cost, String note) {
    SpendEntry e = new SpendEntry();
    e.setCost(cost);
    e.setNote(note);
    return addSpend(session, e);
  }

  public SpendEntry addSpend(SessionEntry session, SpendEntry spend) {
    spend.setSessionId(session.getId());
    session.getMoneySpend().add(spend);
    super.addOrUpdate(spend);
    return spend;
  }
  /**
   * @param spend must have sessionId
   */
  public void deleteSpendAndRelationship(int spendId) {
    SpendEntry spend = find(spendId);
    SessionEntry session = sessionDao.find(spend.getSessionId());
    if (session != null) {
      session.getMoneySpend().remove(spend);
      spend.setSessionId(null);
    }
    super.delete(spendId);
  }
}
